﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

namespace GdHotel.Data.Helpers
{
    public static class FilesHelper
    {
        public static String SavePhoto(this HttpPostedFileBase file, String directory, HttpServerUtilityBase server)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(server.MapPath(directory), fileName);

                if (File.Exists(path))
                {
                    var suffix = Guid.NewGuid().ToString("N").Substring(0, 10);
                    var match = Regex.Match(fileName, "^(?<Name>.+)[.](?<Extension>.*)$");
                    fileName = "{0}{1}.{2}".F(match.Groups["Name"].Value, suffix, match.Groups["Extension"].Value);
                    path = Path.Combine(server.MapPath(directory), fileName);
                }

                file.SaveAs(path);

                var url = Path.Combine(directory, fileName);
                return url;
            }
            return "";
        }
         
    }
}